# -*- coding: utf-8 -*-
import time

import paramiko
from time import sleep
import requests
import xlrd
import xlwt
from pprint import pprint

class MyTets():

    '''创建报告'''
    def new_report(self):
        borders = xlwt.Borders()  # Create borders

        borders.left = 1
        borders.right = 1
        borders.top = 1
        borders.bottom = 1

        pattern_fail = xlwt.Pattern()
        pattern_fail.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern_fail.pattern_fore_colour = 2  # 红色
        self.style_fail = xlwt.XFStyle()
        self.style_fail.pattern = pattern_fail
        self.style_fail.borders = borders

        pattern_pass = xlwt.Pattern()
        pattern_pass.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern_pass.pattern_fore_colour = 3  # 绿色
        self.style_pass = xlwt.XFStyle()
        self.style_pass.pattern = pattern_pass
        self.style_pass.borders = borders

        pattern_first = xlwt.Pattern()
        pattern_first.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern_first.pattern_fore_colour = 52  # 橘色
        self.style_first = xlwt.XFStyle()
        self.style_first.pattern = pattern_first
        self.style_first.borders = borders

        self.workbook = xlwt.Workbook(encoding='utf-8')
        self.worksheet = self.workbook.add_sheet('sheet1')
        self.worksheet.write(0, 0, '系统', self.style_first)
        self.worksheet.write(0, 1, 'IP', self.style_first)
        self.worksheet.write(0, 2, '日志详情', self.style_first)
        self.worksheet.write(0, 3, '部署结果', self.style_first)
        self.worksheet.write(0, 4, '卸载详情', self.style_first)
        self.worksheet.write(0, 5, '卸载结果', self.style_first)

'''ssh连接'''
def connect_device_bash_linux(send_host, host_user, host_password, host_port=22):
    trans = paramiko.Transport((send_host, host_port))
    trans.start_client()
    trans.auth_password(username=host_user, password=host_password)
    channel = trans.open_session()
    channel.settimeout(720000000)
    channel.get_pty()
    channel.invoke_shell()
    return channel

def run_test02():
    channel = connect_device_bash_linux('10.75.2.31','root','admin!@#12345')
    channel.send('mkdir -p agent_tmp && cd agent_tmp && curl --insecure -H "Authorization: Bearer MjcwNTYyNjc3MTU5OTk1MzYyNDoxMDA4MDE6OTRjOGFlNGQtOWEwMC00NGIwLTgzZmItNzM3YWJhNjk2Nzgy" https://10.75.2.37/flowagent/v1/device/download/arm -o package.tar.gz && tar xzvf package.tar.gz && chmod +x install && sudo ./install -c 10.75.2.37 --manager_port=8900\n')
    sleep(6)
    rst = channel.recv(1024000).decode('utf-8')
    print(rst)
    channel.send('enp1s0\n')
    sleep(6)
    channel.send('y\n')
    sleep(6)
    rst2 = channel.recv(1024000).decode('utf-8')
    print(rst2)
    channel.close()

'''读取表格'''
def read_excel(read_file_path, sheet):
    all_data_list = []
    wd = xlrd.open_workbook(read_file_path)
    sheet = wd.sheet_by_name(sheet)
    first_row = sheet.row_values(0)
    for index in range(sheet.nrows):
        if index == 0:
            continue
        # print(sheet.row_values(index))
        every_dict = {}
        for key, value in zip(first_row, sheet.row_values(index)):
            every_dict[key] = value
        all_data_list.append(every_dict)
    # print(all_data_list)
    return all_data_list

'''启动Agent插件'''
def on_Agent_arm(channel, network):
    channel.send(
        'mkdir -p agent_tmp && cd agent_tmp && curl --insecure -H "Authorization: Bearer MjcwNTYyNjc3MTU5OTk1MzYyNDoxMDA4MDE6NDgyMzc5NTQtZjQ4OS00ZDEyLWIyNzctY2IxNTE2YjczZjEy" https://10.75.2.37/flowagent/v1/device/download/arm -o package.tar.gz && tar xzvf package.tar.gz && chmod +x install && sudo ./install -c 10.75.2.37 --manager_port=8900\n')
    sleep(3)
    rst = channel.recv(1024000).decode('utf-8')
    print(rst)
    channel.send(f'{network}\n')
    sleep(2)
    channel.send('y\n')
    sleep(5)
    rst2 = channel.recv(1024000).decode('utf-8')
    print(rst2)

'''启动Agent插件'''
def on_Agent_x86(channel, network):
    channel.send(
        'mkdir -p agent_tmp && cd agent_tmp && curl --insecure -H "Authorization: Bearer MjcwNTYyNjc3MTU5OTk1MzYyNDoxMDA4MDE6NDgyMzc5NTQtZjQ4OS00ZDEyLWIyNzctY2IxNTE2YjczZjEy" https://10.75.2.37/flowagent/v1/device/download/x86 -o package.tar.gz && tar xzvf package.tar.gz && chmod +x install && sudo ./install -c 10.75.2.37 --manager_port=8900\n')
    sleep(3)
    rst = channel.recv(1024000).decode('utf-8')
    print(rst)
    channel.send(f'{network}\n')
    sleep(2)
    channel.send('y\n')
    sleep(5)
    rst2 = channel.recv(1024000).decode('utf-8')
    print(rst2)

'''更改配置文件为vxlan'''
def updata_config_vxlan(channel):
    channel.send("sed -i 's/true/true_up/g' /usr/local/collection_agent/etc/config.yaml\n")
    sleep(1)
    channel.send("sed -i 's/false/true/g' /usr/local/collection_agent/etc/config.yaml\n")
    sleep(1)
    channel.send("sed -i 's/true_up/false/g' /usr/local/collection_agent/etc/config.yaml\n")
    sleep(1)
    channel.send("sed -i 's/4748/4789/g' /usr/local/collection_agent/etc/config.yaml\n")
    sleep(1)
    channel.send("systemctl stop collection_agent.service\n")
    sleep(2)
    channel.send("systemctl start collection_agent.service\n")
    sleep(2)

'''卸载Agent插件'''
def uninstall_Agent(channel):
    channel.send("bash /usr/local/collection_agent/script/uninstall.sh\n")
    sleep(2)
    channel.send("y\n")
    sleep(2)

'''校验：卸载后校验'''
def uninstall_Agent_check(channel, worksheet, row, write_pass, write_fail):
    channel.send("cd /usr/local/collection_agent\n")
    sleep(2)
    rst = channel.recv(1024000).decode('utf-8')
    print(rst)
    # 卸载 Agent，校验卸载
    if '没有那个文件或目录' in rst or 'No such file or directory' in rst:
        print('卸载成功')
        worksheet.write(row, 4, rst)
        worksheet.write(row, 5, '卸载通过', write_pass)
    else:
        print('卸载失败')
        worksheet.write(row, 4, rst)
        worksheet.write(row, 5, '卸载失败', write_fail)
    row += 1
    return row

'''清除日志'''
def clear_log(api_ip):
    send = requests.post(f'https://{api_ip}/apisec/v1/log-clear/log-clear',
                         data={'type': 'accesslog'},
                         headers={'Authorization': token},
                         verify=False)
    print(send.status_code)
    print(send.json())

'''获取日志'''
def get_log(api_ip):
    send = requests.get(f'https://{api_ip}/apisec/v1/access-log?query=&offset=0&limit=20&start_time=2023-01-05+00:00:01&end_time=2023-03-05+23:59:59&sort=desc',
                        headers={'Authorization': token},
                        verify=False)
    #pprint(send.json())
    return send.json()['data']['items']

'''请求服务器，产生日志'''
def send_http(url):
    send = requests.get(url)
    print(send.status_code)

'''校验日志'''
def check_log(log_list, system, ip, worksheet, row, write_pass, write_fail):
    # 校验是否产生相应日志
    have = False
    if log_list:
        for i in log_list:
            dipv4 = i['dipv4']
            #print(dipv4)
            if ip == dipv4:
                have = True
                print(i)
                print('pass')
                worksheet.write(row, 0, system)
                worksheet.write(row, 1, ip)
                worksheet.write(row, 2, f'{i}')
                worksheet.write(row, 3, '部署采集通过', write_pass)
                return
        worksheet.write(row, 0, system)
        worksheet.write(row, 1, ip)
        worksheet.write(row, 2, '')
        worksheet.write(row, 3, '部署采集失败', write_fail)
    elif log_list == []:
        print('检测系统无日志')
        worksheet.write(row, 0, system)
        worksheet.write(row, 1, ip)
        worksheet.write(row, 2, '检测系统未接收到日志')
        worksheet.write(row, 3, '部署采集失败', write_fail)
    print(have)

'''主程序'''
def run_test01():
    API_ip = '10.75.2.37'
    row = 1
    report = MyTets()
    report.new_report()
    all_data_list = read_excel(r'F:\lanxin_download\LxResource\Docs\2022-12/各个系统用户名密码 (1).xlsx', 'Sheet2')
    print(all_data_list)
    for every_ip_passwd in all_data_list:
        clear_log(API_ip)   # 清理日志
        system = every_ip_passwd['系统']
        ip = every_ip_passwd['ip地址']
        user = every_ip_passwd['用户名']
        passwd = every_ip_passwd['密码']
        network = every_ip_passwd['网卡']
        url = every_ip_passwd['访问地址']
        channel = connect_device_bash_linux(ip, user, passwd)
        if 'arm' in system:
            on_Agent_arm(channel, network)    # 部署Agent上线
        elif 'x86' in system:
            on_Agent_x86(channel, network)    # 部署Agent上线
        sleep(5)
        send_http(url) # 请求Agent服务器产生流量
        sleep(30)
        log_list = get_log(API_ip)
        check_log(log_list, system, ip, report.worksheet, row, report.style_pass, report.style_fail)
        uninstall_Agent(channel)    # 卸载Agent
        time.sleep(5)
        row = uninstall_Agent_check(channel, report.worksheet, row, report.style_pass, report.style_fail)  # 校验卸载

        channel.close() # 关闭连接
    report.workbook.save('Agent通路测试结果0002.xlsx')
#read_excel(r'F:\lanxin_download\LxResource\Docs\2022-12/各个系统用户名密码 (1).xlsx', 'Sheet2')
# 说明： 注意设备用例表格需要注明 x86 或 arm
token = "Bearer MjcwNTYyNjc3MTU5OTk1MzYyNDoxMDA4MDE6NDgyMzc5NTQtZjQ4OS00ZDEyLWIyNzctY2IxNTE2YjczZjEy"   # API检测系统对应的token
run_test01()